<template>
  <basic-container class="message-template" v-loading="loading" element-loading-text="数据加载中...">
    <dataList
      ref="roleCrud"
      openIndex
      :pageInfo="pager"
      operaColumnWidth="120"
      :listData="tableData"
      :dataInfo="dataInfo"
      :operaInfo="operaInfo"
      :menuList="menuList"
      :listLayout="['menu']"
      @btn-click="handleBtnClick"
      @menu-click="handleMenuClick"
    ></dataList>
    <v-dialog
      :title="isEdit ? '编辑' : '新增'"
      :show.sync="dialogVisible"
      class="dialogForm"
      width="1000px"
      v-loading="dialogLoading"
      @beforeClose="beforeClose"
      element-loading-text="正在保存..."
      v-if="dialogVisible"
    >
      <el-form ref="message" :model="tableOption" label-width="80px" :rules="tableOption_rules">
        <el-form-item label="模板名称" prop="moduleName">
          <el-input v-halfCharCode v-model="tableOption.moduleName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板编码" prop="moduleCode">
          <el-input v-halfCharCode v-model="tableOption.moduleCode" placeholder="请输入模板编码" />
        </el-form-item>
        <el-form-item label="消息链接" prop="url">
          <el-input v-halfCharCode v-model="tableOption.url" placeholder="请输入消息链接" />
        </el-form-item>
        <el-form-item label="打开方式" prop="openType">
          <el-select clearable placeholder="请选择打开方式" v-model="tableOption.openType">
            <el-option v-for="item in openTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息模板" prop="template">
          <el-input v-halfCharCode type="textarea" :autosize="{ minRows: 2, maxRows: 8}" v-model="tableOption.template" placeholder="请输入消息模板" />
        </el-form-item>
      </el-form>
      <span slot="foot">
        <el-button v-throttle="[commit]">{{isEdit ? '修 改' : '保 存'}}</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </v-dialog>
  </basic-container>
</template>

<script>
import { fetchTemplateList, addTemplate, putTemplate, delTemplate } from '~/admin/api/message'
export default {
  name: "message-template",
  provide () {
    return {
      initList: this.getListData
    };
  },
  beforeMount () {
    this.getListData()
    this.openTypes = this.getDict('open_type')
  },
  data () {
    return {
      tableData: [],
      // 请求参数
      params: {
        current: 1,
        size: 10
      },
      // 分页
      pager: {
        total: 0, // 总页数
        current: 1, // 当前页数
        size: 10 // 每页显示多少条
      },
      // 页面loading
      loading: false,
      openTypes: [],
      // 新增、编辑弹框
      isEdit: false,
      dialogLoading: false,
      dialogVisible: false,
      tableOption: {
        moduleName: '',
        moduleCode: '',
        url: '',
        openType: '',
        template: ''
      },
      tableOption_rules: {
        moduleName: [{ required: true, message: '请输入模板名称', trigger: 'blur' },
        { min: 0, max: 25, message: '长度在 0 到 25 个字符', trigger: 'blur' }],
        moduleCode: [{ required: true, message: '请输入模板编码', trigger: 'blur' },
        { min: 0, max: 25, message: '长度在 0 到 25 个字符', trigger: 'blur' }],
        url: [{ required: false, message: '请输入消息链接', trigger: 'blur' },
        { min: 0, max: 25, message: '长度在 0 到 25 个字符', trigger: 'blur' }],
        template: [{ required: false, message: '请输入消息模板', trigger: 'blur' },
        { min: 0, max: 225, message: '长度在 0 到 225 个字符', trigger: 'blur' }]
      }
    }
  },
  computed: {
    menuList () {
      return this.getPermissions('messageConfig_edit') ? [{ add: '添加模板' }] : []
    },
    // 权限配置
    permissionList () {
      return {
        editBtn: this.getPermissions('messageConfig_edit'),
        delBtn: this.getPermissions('messageConfig_del')
      }
    },
    // 配置表头
    dataInfo () {
      return [
        { label: '模板名称', prop: 'moduleName', width: '220', 'show-overflow-tooltip': true },
        { label: '模板编码', prop: 'moduleCode', width: '220', 'show-overflow-tooltip': true },
        { label: '消息链接', prop: 'url', width: '280', 'show-overflow-tooltip': true },
        { label: '打开方式', prop: 'openType', formatter: this.getOpenType, width: '120' },
        { label: '消息模板', prop: 'template', width: '460', 'show-overflow-tooltip': true }
      ]
    },
    // 操作项配置
    operaInfo () {
      return [
        { label: '编辑', name: 'edit', verify: () => this.permissionList.editBtn },
        { label: '删除', name: 'delete', verify: () => this.permissionList.delBtn },
      ]
    }
  },
  methods: {
    // 获取列表
    getListData (params = {}) {
      this.loading = true;
      let requestData = { ...this.params, ...params };
      fetchTemplateList(requestData)
        .then(res => {
          const { current, size, total, records } = res.data.data;
          this.tableData = records;
          this.params = requestData;
          this.pager = { total, current, size };
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 菜单点击监听
    handleMenuClick (type) {
      switch (type) {
        case "add":
          this.handleCreate();
          break;
        default:
          this.$message(type);
          break;
      }
    },
    // 按钮点击监听
    handleBtnClick ({ type, row }) {
      switch (type) {
        case 'edit':
          this.handleUpdate(row)
          break;
        case 'delete':
          this.handleDelete(row)
          break;
        default:
          break;
      }
    },
    // 编辑
    handleUpdate (row) {
      this.tableOption = row
      this.isEdit = true
      this.dialogVisible = true
    },
    // 删除
    handleDelete (row) {
      this.$confirm('是否确认删除' + row.moduleName, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delTemplate(row.uuid)
      }).then(() => {
        this.getListData()
        this.$notify.success('删除成功')
      })
    },
    // 弹框保存
    commit () {
      this.$refs.message.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          if (this.isEdit) {
            putTemplate(this.tableOption).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('修改成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('修改失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          } else {
            addTemplate(this.tableOption).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('添加成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('添加失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          }
        }
      })
    },
    // 弹框取消
    handleCancel () {
      Object.keys(this.tableOption).forEach(key => {
        if (this.tableOption[key]) {
          if (this.tableOption[key] instanceof Array) {
            this.tableOption[key] = []
          } else if (typeof this.tableOption[key] === 'string' || typeof this.tableOption[key] === 'number') {
            this.tableOption[key] = ''
          }
        }
      })
      this.dialogVisible = false
      this.isEdit = false
      this.getListData()
    },
    beforeClose (done) {
      this.handleCancel()
    },
    // 新增
    handleCreate () {
      this.dialogVisible = true
    },
    // 打开方式初始化
    getOpenType (row, column, cellValue) {
      let obj = this.openTypes.find(p => p.value == cellValue);
      if (obj) {
        return obj.label;
      }
      return "";
    },
  }
}
</script>

<style scoped lang="scss">
.message-template {
  .dialogForm {
    @include formWrap(2);
  }
}
</style>

